package com.ufox.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ufox.entity.Orders;
import com.ufox.entity.Products;
import com.ufox.entity.Result;
import com.ufox.entity.User;
import com.ufox.req.PasswordREQ;
import com.ufox.req.UserREQ;
import com.ufox.service.IUserService;
import com.ufox.utils.JWTUtil;
import com.ufox.utils.JWTUtils;
import com.ufox.utils.MD5Util;
import com.ufox.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 优狐科技-www.hbufox.com
 * @since 2022-06-09
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService iuserService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${login_url}")
    private String loginUrl;

    @Autowired
    private JWTUtils jwtUtil;


    @PostMapping("/regist/{uuid}")
    public Result updateOrAdd(@RequestBody User user,
                              @PathVariable String uuid) {

        //1 获取id
        if (StrUtil.isBlank(uuid)) {
            return Result.error("验证码错误");
        }

        if (StrUtil.isBlank(user.getCode())) {
            return Result.error("请输入验证码");
        }

        //2 根据id 查询
        String redisUuid = (String) redisUtils.get(uuid);
        if (!user.getCode().equals(redisUuid)) {
            return Result.error("验证码错误");
        }


        return iuserService.regist(user);
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserREQ userREQ) {

        //log.info(username+"---"+password);

        //1 获取id
        String id = userREQ.getId();
        if (StrUtil.isBlank(id)) {
            return Result.error("验证码错误");
        }

        String code = userREQ.getCode();
        if (StrUtil.isBlank(code)) {
            return Result.error("请输入验证码");
        }

        //2 根据id 查询
        String uuid = (String) redisUtils.get(id);
        if (!code.equals(uuid)) {
            return Result.error("验证码错误");
        }

        //3 判断

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, userREQ.getUsername());

        String passWord = MD5Util.getMD5String(userREQ.getPassword());
        wrapper.eq(User::getPassword, passWord);

        User user = iuserService.getOne(wrapper);
        if (user == null) {
            return Result.error("用户名或密码错误");
        } else {
            if (user.getState() == 0) {
                return Result.error("该账号未激活,请前往邮箱激活");
            } else {
                HashMap<String, Object> map = new HashMap<>();
                map.put("id", user.getId());
                String token = JWTUtil.getJWT(map);
                return Result.ok(token);
//                return Result.ok( jwtUtil.createJWT("id", user.getId() + ""));
            }

        }
    }

    @RequestMapping("/info")
    public Result info(String token) {

        log.info(token);

        DecodedJWT jwt = JWTUtil.verify(token);
        String id = jwt.getClaim("id").asString();

//        String id = jwtUtil.getPlayload(token,"id");


        //判断 redis数据中有没有登录用户的id 相同,

        //获取到了所有 以Bearer  开头的键
        Set<String> keys = redisTemplate.keys("Bearer *");
        for (String key : keys) {

            //截取掉Bearer
            key = key.substring(7);

            //从token中获取id
            DecodedJWT verify = JWTUtil.verify(key);
            String tokenId = verify.getClaim("id").asString();

            if (id.equals(tokenId)) {
                //把之前登录用户的token删除
                redisUtils.del("Bearer " + key);
                break;
            }
        }

        User user = iuserService.getById(id);
        if (user == null) {
            return Result.error("获取用户失败");
        } else {
            //登录成功以后,后台也保存用户的登录状态
            String ss = JSONUtil.toJsonStr(user);
            redisUtils.set("Bearer " + token, ss, 3600);
            return Result.ok(user);
        }
    }


    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        //根据 id  token 从数据库删除数据
        //获取请求头中token
        String token = request.getHeader("Authorization");
        if(StrUtil.isNotBlank(token)){
            redisUtils.del(token);
        }

        return Result.ok();
    }

    @GetMapping("/active/{statecode}")
    public void active(@PathVariable String statecode, HttpServletResponse response) throws IOException {

        //1 获取statecode
        //2 激活
        //3 页面跳转
        //1 获取激活码
        //2 激活
        //3 重定向到登录界面
        iuserService.updateUserByCode(statecode);
//        ModelAndView mv = new ModelAndView("redirect:http://192.168.4.79:8099/login?id");
//        ModelAndView mv = new ModelAndView("redirect:"+loginUrl+"login?id");
//        ModelAndView mv = new ModelAndView("redirect:http://192.168.0.103:8099/login");

//        return mv;
        response.sendRedirect(loginUrl + "login?id");
    }


    /**
     * 校验原密码是否正确
     *
     * @return
     */
    @PostMapping("/pwd")
    public Result checkPassword(@RequestBody PasswordREQ req) {
        return iuserService.checkPassword(req);
    }


    /**
     * 修改密码
     *
     * @return
     */
    @PutMapping("/pwd")
    public Result updatePassword(@RequestBody PasswordREQ req) {
        return iuserService.updatePassword(req);
    }


    @GetMapping("/username/{username}")
    protected Result findByUserName(@PathVariable String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(username), User::getUsername, username);
        List<User> list = iuserService.list(wrapper);

        Result result = Result.ok();
        if (list.size() > 0) {
            result.setFlag(false);
        } else {
            result.setFlag(true);
        }
        return result;
    }


    //顾客订单
    @GetMapping("/orders/{userId}")
    public Result getOrdersByUserId(@PathVariable String userId) {
        List<Orders> list = iuserService.getOrdersByUserId(userId);
        return Result.ok(list);
    }

    //商家订单
    @GetMapping("/orders/cust/{userId}")
    public Result getCustOrdersByUserId(@PathVariable String userId) {
//        List<Orders> list = iuserService.getCustOrdersByUserId(userId);
//        return Result.ok(list);
        return iuserService.getCustOrdersByUserId(userId);
    }

}

